﻿using Dal.DTO;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dal
{
    public class ShopDal
    {
        public ShopDal(MyContext context)
        {
            Context = context;
        }

        public MyContext Context { get; }
        /// <summary>
        /// 添加门店
        /// </summary>
        /// <param name="shop">一个门店对象</param>
        /// <returns>受影响行数</returns>
        public int Add(Shop shop)
        {
            if (Context.Shop.Any(x => x.phone == shop.phone))
            {
                return -1;
            }
            shop.del = false;
            Context.Shop.Add(shop);
            return Context.SaveChanges();
        }
        /// <summary>
        /// 修改门店
        /// </summary>
        /// <param name="shop">一个门店对象</param>
        /// <returns>受影响行数</returns>
        public int Update(Shop shop)
        {
            if (Context.Shop.Any(x => x.phone == shop.phone))
            {
                return -1;
            }
            shop.del = false;
            Context.Shop.Update(shop);
            return Context.SaveChanges();
        }
        /// <summary>
        /// 逻辑删除门店
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns>受影响行数</returns>
        public int Delete(int id)
        {
            //通过id查出一个门店对象
            var shop = Context.Shop.Find(id);
            shop.del=true;
            return Context.SaveChanges();
        }
        /// <summary>
        /// 分页显示，门店名称模糊查，门店地址精确查
        /// </summary>
        /// <param name="index">当前页</param>
        /// <param name="size">页容量</param>
        /// <param name="name">门店名称</param>
        /// <param name="addr">门店地址</param>
        /// <returns></returns>
        public ShopDTO GetAll(int index,int size,string? name,string? addr)
        {
            var s = Context.Shop.Where(x=>x.del==false).AsQueryable();
            if(!string.IsNullOrEmpty(name))
            {
                s = s.Where(x=>x.name.Contains(name));
            }
            if (!string.IsNullOrEmpty(addr))
            {
                s = s.Where(x=>x.addr==addr);
            }
            var dto=new ShopDTO();
            dto.count = s.Count();
            dto.data = s.OrderBy(x=>x.id).Skip((index-1)*size).Take(size).ToList();
            return dto;
        }
        /// <summary>
        /// 通过id获取一个门店对象
        /// </summary>
        /// <param name="id">门店id</param>
        /// <returns>一个门店对象</returns>
        public Shop GetShop(int id)
        {
            return Context.Shop.Find(id);
        }
        /// <summary>
        /// 查所有地址
        /// </summary>
        /// <returns>地址集合</returns>
        public List<Addr> GetAddrs()
        {
            return Context.Address.ToList();
        }
    }
}
